package myServer.serverCore;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Data;
import myServer.handler.ChatTransmitHandler;
import myServer.handler.LoginRequestHandler;
import myServer.handler.ServerExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import protobuf.codec.MyProtobufDecoder;
import protobuf.codec.MyProtobufEncoder;

import java.net.InetSocketAddress;

@Data
@Service("ChatServer")
public class ChatServer {

    //服务器 IP
    @Value("${server.ip}")
    private String ip;
    //服务器 端口
    @Value("${server.port}")
    private int port;
    @Autowired
    private LoginRequestHandler loginRequestHandler;
    @Autowired
    private ServerExceptionHandler serverExceptionHandler;
    @Autowired
    private ChatTransmitHandler chatTransmitHandler;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServerBootstrap serverBootstrap = new ServerBootstrap();

    public void run() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        serverBootstrap
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new MyProtobufDecoder())
                                .addLast(new MyProtobufEncoder())
                                .addLast("login", loginRequestHandler)
                                .addLast(serverExceptionHandler);
                    }
                });
        try {
            ChannelFuture channelFuture = serverBootstrap
                    .localAddress(new InetSocketAddress(ip, port))
                    .bind()
                    .sync();

            System.out.println(
                    "服务端启动, 端口 :" +
                            channelFuture.channel().localAddress());

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
